package com.heisen.uua.service.impl;

import com.heisen.base.entity.Api;
import com.heisen.base.entity.SystemUser;
import com.heisen.security.entity.UuaUser;
import com.heisen.systemapi.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
@Slf4j
public class XmUserDetailServiceImpl implements UserDetailsService {


    @Resource
    private UserService userService;
    /**
     *  用户登入
     * @param username 用户名
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("【准备登入.....】 {}" ,username);
        Api<SystemUser> userApi = userService.LoginByName(username);
        if(userApi.getCode().equals(1)){
            SystemUser systemUser = userApi.getData();
            if (systemUser != null) {
                    boolean notLocked = false;
                    if (StringUtils.equals(SystemUser.STATUS_VALID, systemUser.getStatus()))
                        notLocked = true;
                    UuaUser uuaUser = new UuaUser(systemUser.getUsername(), systemUser.getPassword(), true, true, true, notLocked,
                            AuthorityUtils.commaSeparatedStringToAuthorityList(systemUser.getPermissions()));

                    return transSystemUserToAuthUser(uuaUser,systemUser);
            }
        }
        throw new UsernameNotFoundException("登入失败");
    }



    private UuaUser transSystemUserToAuthUser( UuaUser uuaUser, SystemUser systemUser) {
        uuaUser.setAvatar(systemUser.getAvatar());
        uuaUser.setDeptId(systemUser.getDeptId());
        uuaUser.setDeptName(systemUser.getDeptName());
        uuaUser.setEmail(systemUser.getEmail());
        uuaUser.setMobile(systemUser.getMobile());
        uuaUser.setRoleId(systemUser.getRoleId());
        uuaUser.setRoleName(systemUser.getRoleName());
        uuaUser.setSex(systemUser.getSex());
        uuaUser.setUserId(systemUser.getUserId());
        uuaUser.setLastLoginTime(systemUser.getLastLoginTime());
        uuaUser.setDescription(systemUser.getDescription());
        uuaUser.setStatus(systemUser.getStatus());
        return uuaUser;
    }


}
